<?php
    class Thaind_Acl extends Zend_Acl
    {
        public function __construct($auth)
        {
        	Zend_Loader::loadClass("Admin_Models_UserModel");
        	Zend_Loader::loadClass("Admin_Models_ControllerModel");
        	Zend_Loader::loadClass("Admin_Models_RoleModel");
        	
        	$user_admin_model = new Admin_Models_UserModel();
        	$controller_model = new Admin_Models_ControllerModel();
        	$role_model = new Admin_Models_RoleModel();
        	
        	$controller_list = $controller_model->fetchAll();
        	$user_list = $user_admin_model->fetchAll();
        	$role_list = $role_model->getRoleList();
        	if ($controller_list) {
        		$controller_list = $controller_list->toArray();
        		foreach ($controller_list as $controller) {
        			if (!$this->has(new Zend_Acl_Resource($controller['controller']))){
	        			$this->add(new Zend_Acl_Resource($controller['controller']));
        			}
        		}
	        	if ($user_list) {
	        		$user_list = $user_list->toArray();
	        		foreach ($user_list as $user) {
	        			if (!$this->hasRole(new Zend_Acl_Role($user['username']))){
		        			$this->addRole(new Zend_Acl_Role($user['username']));
	        			}
	        		}
	        	}
        	}
        	if ($role_list) {
        		foreach ($role_list as $role) {
        			$action_list = explode(',', $role['action']);
        			foreach ($action_list as $action) {
        				$this->allow($role['username'],$role['controller'],$action);
        			}
        		}
        	}
        	$permission_manager_list = $user_admin_model->getPermissionManagerList();
        	if (!$this->has(new Zend_Acl_Resource('admin:permission'))){
        		$this->add(new Zend_Acl_Resource('admin:permission'));
        	}
        	if (!$this->hasRole(new Zend_Acl_Role('sauthienthu'))){
        		$this->addRole(new Zend_Acl_Role('sauthienthu'));
        	}
        	$this->allow('sauthienthu','admin:permission',array("add-permisstion-manager","add-controller","add-action"));
			foreach ($permission_manager_list as $value) {
				$this->allow($value['username'],'admin:permission','index');
			}
        }
    }